<template>
  <div class="relative w-full h-full">
    <PageHeader :title="t('goods_list.商品管理')" />
    <el-radio-group v-model="filters.status" class="mb10">
      <el-radio-button :label="t('goods_list.审核中商品')" value="0" />
      <el-radio-button :label="t('goods_list.已发布商品')" value="1" />
      <el-radio-button :label="t('goods_list.已驳回商品')" value="-1" />
      <el-radio-button :label="t('goods_list.已下架商品')" value="-2" />
    </el-radio-group>
    <div class="mt10">
      <el-input
        v-model="filters.name"
        class="mr10 mb10"
        :placeholder="t('goods_list.请输入')"
        style="width: 256px"
      >
        <template #prefix>
          <span class="color-555555">{{ t('goods_list.商品名称') }}</span>
        </template>
      </el-input>
      <el-input
        v-model="filters.itemCode"
        class="mr10 mb10"
        :placeholder="t('goods_list.请输入')"
        style="width: 256px"
      >
        <template #prefix>
          <span class="color-555555">{{ t('goods_list.货号') }}</span>
        </template>
      </el-input>
      <el-cascader
        class="mr10 mb10"
        v-model="filters.skuClassify"
        :options="skuClassifyOptions"
        :props="{ label: 'name' + locale, value: 'id' }"
        :placeholder="t('goods_list.请选择分类')"
      />
      <el-date-picker
        v-model="filters.date"
        class="mr10 mb10 flex-grow-0"
        type="daterange"
        :range-separator="t('goods_list.至')"
        :start-placeholder="t('goods_list.发布开始日期')"
        :end-placeholder="t('goods_list.发布结束日期')"
        style="width: 300px"
        value-format="YYYY-MM-DD"
      />
      <div class="inline-flex float-right">
        <el-button @click="resetFilters">{{ t('goods_list.重置') }}</el-button>
        <el-button type="primary" @click="handSearch">{{ t('goods_list.查询') }}</el-button>
      </div>
    </div>
    <div class="mt12 toolbar flex_aic pr12">
      <div class="addBtn flex_aic_jcc" @click="handleRelease">
        <SvgIcon name="icondaoru" class="mr8" color="rgb(250, 111, 30)" />
        <span>{{ t('goods_list.发布商品') }}</span>
      </div>
      <template v-if="filters.status == 0">
        <!-- <div class="addBtn flex_aic_jcc ml12" @click="handleBatchAudit(1)">
          <SvgIcon name="iconziyuan31" class="mr8" color="rgb(249, 160, 6)" />
          <span>{{ t('goods_list.批量审核通过') }}</span>
        </div>
        <div class="addBtn flex_aic_jcc ml12" @click="handleBatchAudit(2)">
          <SvgIcon name="iconziyuan31" class="mr8" color="rgb(249, 160, 6)" />
          <span>{{ t('goods_list.批量驳回') }}</span>
        </div> -->
      </template>
      <template v-if="filters.status == 1">
        <div
          class="addBtn flex_aic_jcc ml12"
          @click="handleBatchAudit(3)"
          v-my-point="'sku:off'"
        >
          <SvgIcon name="iconziyuan31" class="mr8" color="rgb(249, 160, 6)" />
          <span>{{ t('goods_list.批量下架') }}</span>
        </div>
        <!-- <div class="addBtn flex_aic_jcc ml12" @click="handleBatchAudit(5)">
          <SvgIcon name="iconziyuan31" class="mr8" color="rgb(249, 160, 6)" />
          <span>{{ t('goods_list.批量推荐') }}</span>
        </div>
        <div class="addBtn flex_aic_jcc ml12" @click="handleBatchAudit(6)">
          <SvgIcon name="iconziyuan31" class="mr8" color="rgb(249, 160, 6)" />
          <span>{{ t('goods_list.批量取消推荐') }}</span>
        </div> -->
        <div
          class="addBtn flex_aic_jcc ml12"
          @click="handleBatchAudit(7)"
          v-my-point="'sku:del'"
        >
          <SvgIcon name="iconziyuan31" class="mr8" color="rgb(249, 160, 6)" />
          <span>{{ t('goods_list.批量删除') }}</span>
        </div>
      </template>
      <template v-if="filters.status == -1">
        <div
          class="addBtn flex_aic_jcc ml12"
          @click="handleBatchAudit(7)"
          v-my-point="'sku:del'"
        >
          <SvgIcon name="iconziyuan31" class="mr8" color="rgb(249, 160, 6)" />
          <span>{{ t('goods_list.批量删除') }}</span>
        </div>
      </template>
      <template v-if="filters.status == -2">
        <div
          class="addBtn flex_aic_jcc ml12"
          @click="handleBatchAudit(4)"
          v-my-point="'sku:on'"
        >
          <SvgIcon name="iconziyuan31" class="mr8" color="rgb(249, 160, 6)" />
          <span>{{ t('goods_list.批量上架') }}</span>
        </div>
        <div
          class="addBtn flex_aic_jcc ml12"
          @click="handleBatchAudit(7)"
          v-my-point="'sku:del'"
        >
          <SvgIcon name="iconziyuan31" class="mr8" color="rgb(249, 160, 6)" />
          <span>{{ t('goods_list.批量删除') }}</span>
        </div>
      </template>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      class="cover-table mt12"
      height="calc(100% - 280px)"
      row-key="id"
      @selection-change="handleSelectionChange"
      border
      v-loading="loading"
    >
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column :label="t('goods_list.序号')" type="index" width="80" />
      <el-table-column prop="name" :label="t('goods_list.商品信息')" width="500">
        <template #default="scope">
          <div class="flex">
            <el-popover placement="right" width="226" trigger="hover">
              <div
                class="bigImg"
                :style="{ 'background-image': `url(${scope.row.image})` }"
              ></div>
              <template #reference>
                <div
                  class="goodImg"
                  :style="{ 'background-image': `url(${scope.row.image})` }"
                ></div>
              </template>
            </el-popover>

            <div class="ml10 flex_fdc_jcsb text-left">
              <div class="color-333333 line-2">
                {{ scope.row["name" + locale] }}
              </div>
              <div class="color-666666 fs-12">
                <div class="line-1">{{ getCategoryPath(scope.row) }}</div>
                <div class="line-1">
                  {{ t('goods_list.所属商户') }}：{{ scope.row["tenantName" + locale] || t('goods_list.暂无') }}
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="t('goods_list.商品价格')">
        <template #default="scope">
          {{ formatPrice(scope.row.minPrice) }}
        </template>
      </el-table-column>
      <el-table-column :label="t('goods_list.商品库存')">
        <template #default="scope">
          {{ scope.row.stockSum || 0 }}
        </template>
      </el-table-column>
      <!-- <el-table-column :label="t('goods_list.实际虚拟销量')">
        <template #default="scope">
          {{ scope.row.salesReal || 0 }}/{{ scope.row.salesVirtual || 0 }}
        </template>
      </el-table-column> -->
      <el-table-column :label="t('goods_list.发布时间')">
        <template #default="scope">
          {{ formatDate(scope.row.createdTime) }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="readCount" :label="t('goods_list.已阅读用户数量')">
        <template #default="scope">
          {{ scope.row.readCount || 0 }}
        </template>
      </el-table-column> -->
      <el-table-column :label="t('goods_list.操作')" width="460">
        <template #default="scope">
          <div class="operationBtnRow">
            <el-button type="text" size="small" @click="handleDetail(scope.row)"
              >{{ t('goods_list.查看详情') }}</el-button
            >
            <template v-if="filters.status == 1">
              <!-- 已发布商品 -->
              <el-button
                type="text"
                size="small"
                @click="handleEdit(scope.row)"
                v-my-point="'sku:edit'"
                >{{ t('goods_list.编辑') }}</el-button
              >
            </template>
            <template v-if="filters.status == 0 || filters.status == 1">
              <!-- 待审核 -->
              <el-button
                type="text"
                size="small"
                @click="handleLookSpec(scope.row)"
                >{{ t('goods_list.查看规格') }}</el-button
              >
            </template>
            <template v-if="filters.status == -1">
              <!-- 审核驳回 -->
              <el-button
                type="text"
                size="small"
                @click="handleEdit(scope.row)"
                v-my-point="'sku:edit'"
                >{{ t('goods_list.编辑') }}</el-button
              >
            </template>
            <template v-if="filters.status == -2">
              <el-button
                type="text"
                size="small"
                @click="handleEdit(scope.row)"
                v-my-point="'sku:edit'"
                >{{ t('goods_list.编辑') }}</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="handPut([scope.row.id])"
                v-my-point="'sku:on'"
                >{{ t('goods_list.重新上架') }}</el-button
              >
            </template>

            <template
              v-if="
                filters.status == 1 ||
                filters.status == -1 ||
                filters.status == -2
              "
            >
              <el-popconfirm
                :title="t('goods_list.确定删除吗')"
                @confirm="handleDelete([scope.row.id])"
                :confirm-button-text="t('goods_list.确定')"
                :cancel-button-text="t('goods_list.取消')"
                width="300px"
              >
                <template #reference>
                  <el-button
                    class="ml0"
                    type="text"
                    size="small"
                    v-my-point="'sku:del'"
                    >{{ t('goods_list.删除') }}</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex justify-end mt24 absolute bottom-0 right-0">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <RejectDia
      v-model="rejectDiaVisible"
      :data="currentOperateRow"
      @success="getList()"
    ></RejectDia>
    <SpecDia v-model="specDiaVisible" :data="currentOperateRow"></SpecDia>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import RejectDia from "./rejectDia.vue";
import { useRouter } from "vue-router";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
import moment from "moment";
import SpecDia from "./components/specDia.vue";

const { t, locale } = useI18n();
const router = useRouter();
const rejectDiaVisible = ref(false);
const loading = ref(false);
const selectedRows = ref([]);
const total = ref(0);
// 当前操作的商品数据
const currentOperateRow = ref([]);
const specDiaVisible = ref(false);

// 查询参数
const queryParams = ref({
  page: 1,
  size: 10,
});
const skuClassifyOptions = ref([]);
// 表单筛选条件
const filters = ref({
  name: "",
  itemCode: "",
  date: [],
  status: "1",
  skuClassify: "",
});

watch(
  () => filters.value.status,
  (newVal) => {
    console.log(6666, newVal);
    getList();
  }
);

const tableData = ref([]);

const getSkuClassify = () => {
  Api.getSkuClassify({
    page: 0,
    size: 999,
    parentId: 0,
  }).then((res) => {
    skuClassifyOptions.value = res.data.content || [];
  });
};

// 格式化价格
const formatPrice = (price) => {
  if (!price) return "¥0.00";
  return `¥${parseFloat(price).toFixed(2)}`;
};

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return "--";
  return dayjs(timestamp).format("YYYY-MM-DD HH:mm:ss");
};

// 获取分类路径
const getCategoryPath = (row) => {
  return (
    row[`skuClassify1Name${locale.value}`] +
    "->" +
    row[`skuClassify2Name${locale.value}`]
  );
};

// 获取商品列表
const getList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      ...queryParams.value,
      status: filters.value.status,
      itemCode: filters.value.itemCode,
      page: queryParams.value.page - 1,
      ["name" + locale.value]: filters.value.name,
      lastOnTimeStart: filters.value.date?.[0]
        ? moment(filters.value.date[0]).format("YYYY-MM-DD 00:00:00")
        : undefined,
      lastOnTimeEnd: filters.value.date?.[1]
        ? moment(filters.value.date[1]).format("YYYY-MM-DD 23:59:59")
        : undefined,
      skuClassify1Id: filters.value.skuClassify?.[0],
      skuClassify2Id: filters.value.skuClassify?.[1],
    };

    // 删除不需要传递的参数
    delete params.date;

    const res = await Api.sku_list(params);
    if (res.status === 200) {
      tableData.value = res.data.content || [];
      total.value = Number(res.data.totalElements || 0);
    } else {
      ElMessage.error(res.message || t('goods_list.获取商品列表失败'));
    }
  } catch (error) {
    console.error("获取商品列表失败", error);
    ElMessage.error(t('goods_list.获取商品列表失败'));
  } finally {
    loading.value = false;
  }
};

// 重置筛选条件
const resetFilters = () => {
  filters.value = {
    name: "",
    itemCode: "",
    date: [],
    status: "1", // 保留当前状态筛选
    skuClassify: "",
  };
  queryParams.value.page = 1;
  getList();
};

const handSearch = () => {
  queryParams.value.page = 1;
  getList();
};

// 删除商品
const handleDelete = (ids) => {
  Api.sku_delete(ids).then((res) => {
    if (res.status === 200) {
      ElMessage.success(t('goods_list.删除成功'));
      getList();
    }
  });
};

// 编辑商品
const handleEdit = (row) => {
  router.push({
    path: "/goods/goods_release",
    query: { id: row.id },
  });
};

// 新增商品
const handleRelease = () => {
  router.push("/goods/goods_release");
};

// 分页大小变更
const handleSizeChange = (size) => {
  queryParams.value.size = size;
  getList();
};

// 页码变更
const handleCurrentChange = (page) => {
  queryParams.value.page = page;
  getList();
};

// 表格选择项变更
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 是否可选
const selectable = (row) => {
  return true;
};

// 审核通过
const handlePass = async (ids) => {
  await Api.sku_check({
    ids: ids,
    status: 1,
  }).then((res) => {
    if (res.status === 200) {
      ElMessage.success(t('goods_list.审核通过成功'));
      getList();
    }
  });
};

// 下架商品
const handleRemoval = (ids) => {
  Api.sku_off(ids).then((res) => {
    if (res.status === 200) {
      ElMessage.success(t('goods_list.下架成功'));
      getList();
    }
  });
};

// 驳回上架
const handleReject = (row) => {
  rejectDiaVisible.value = true;
  // 存储当前操作的商品，方便对话框组件使用
  currentOperateRow.value = [JSON.parse(JSON.stringify(row))];
};

// 批量取消推荐
const handleCancelRecommend = (ids) => {
  Api.sku_cancelRecommendList(ids).then((res) => {
    if (res.status === 200) {
      ElMessage.success(t('goods_list.取消推荐成功'));
      getList();
    }
  });
};

// 重新上架
const handPut = async (ids) => {
  Api.sku_on(ids).then((res) => {
    if (res.status === 200) {
      ElMessage.success(t('goods_list.重新上架成功'));
      getList();
    }
  });
};
// 查看驳回原因
const handleLookReason = (row) => {
  rejectDiaVisible.value = true;
  // 只查看模式
  currentOperateRow.value = [{ ...row, viewOnly: true }];
};

const handleBatchAudit = (type) => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning(t('goods_list.请至少选择一个商品'));
    return;
  }
  if (type === 1) {
    handlePass(selectedRows.value.map((item) => item.id));
  } else if (type === 2) {
    rejectDiaVisible.value = true;
    currentOperateRow.value = JSON.parse(JSON.stringify(selectedRows.value));
  } else if (type === 3) {
    handleRemoval(selectedRows.value.map((item) => item.id));
  } else if (type === 4) {
    handPut(selectedRows.value.map((item) => item.id));
  } else if (type === 7) {
    handleDelete(selectedRows.value.map((item) => item.id));
  }
};

const handleDetail = (row) => {
  router.push({
    path: "/goods/goods_list/detail",
    query: { id: row.id },
  });
};

// 查看规格
const handleLookSpec = (row) => {
  specDiaVisible.value = true;
  currentOperateRow.value = JSON.parse(JSON.stringify(row));
};

// 页面加载时获取数据
onMounted(() => {
  getSkuClassify();
  getList();
});
</script>

<style lang="scss" scoped>
.toolbar {
  width: 100%;
  height: 42px;
  margin-bottom: 5px;
  background: rgba(24, 144 ,255, 0.1);
}
.addBtn {
  height: 28px;
  margin-left: 10px;
  padding: 0 7px;
  border-radius: 3px;
  background: #fff;
  cursor: pointer;
}
.split {
  width: 1px;
  height: 12px;
  background: #ddd;
  margin: 0 5px;
}

.goodImg {
  display: inline-block;
  flex-shrink: 0;
  width: 80px;
  height: 80px;
  overflow: hidden;
  border: 1px solid #e2e5f6;
  border-radius: 3px;
  background: #f8f8f8;
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

.bigImg {
  display: inline-block;
  flex-shrink: 0;
  width: 200px;
  height: 200px;
  overflow: hidden;
  // border: 1px solid #e2e5f6;
  // border-radius: 3px;
  // background: #f8f8f8;
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}
</style>
